package com.wkh.datastructure.queue;

import com.wkh.datastructure.SinglyLinkedList;

import java.util.Iterator;

public class LinkedListQueue<E> implements Queue<E>,Iterable<E>{
    private static class Node<E>{
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    private Node<E> head = new Node<>(null,null);//头节点指向哨兵节点
    private Node<E> tail = head;//尾节点也指向哨兵节点
    private int size; //有效节点个数
    private int capacity = Integer.MAX_VALUE; //队列容量

    /**
     * 设置自定义容量
     * @param capacity 队列容量
     */
    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
        //哨兵节点的next也指向哨兵节点
        tail.next = head;
    }

    public LinkedListQueue() {
        //哨兵节点的next也指向哨兵节点
        tail.next = head;
    }

    /**
     * 向队列尾插入值
     *
     * @param value 待插入值
     * @return 插入成功返回true，插入失败返回false
     */
    @Override
    public boolean offer(E value) {
        if (isFull()){
            return false;
        }
        Node<E> newNode = new Node<>(value, head);
        tail.next = newNode;
        tail = newNode;
        size++;
        return true;
    }

    /**
     * 从队列获取值，并移除
     *
     * @return 如果队列非空返回队头值，否者返回null
     */
    @Override
    public E pool() {
        if (isEmpty()){
            return null;
        }
        Node<E> first = head.next;
        head.next = first.next;
        if (first == tail){
            tail = head;
        }
        size--;
        return first.value;
    }

    /**
     * 从队头获取值，不移除
     *
     * @return 如果队列非空返回队头值，否则返回null
     */
    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return head.next.value;
    }

    /**
     * 检查队列是否为空
     *
     * @return 空返回true，否则返回false
     */
    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 检查队列是否已满
     *
     * @return 满了返回true，否则返回false
     */
    @Override
    public boolean isFull() {
        return size >= capacity;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p!=head;
            }

            @Override
            public E next() {
                E value = p.value;
                 p = p.next;
                return value;
            }
        };
    }
}
